<template>
	<view class="container">
		<!-- 店铺展示部分 -->
		<!-- <image :src="shopImage" mode="widthFix"></image> -->
		<view class="swiper-container">
			<!-- 轮播图 -->
			<swiper class="swiper-box" :autoplay="true" :interval="3000" :duration="500" :circular="true" indicator-dots
				indicator-color="#fff" indicator-active-color="#0086d6">
				<swiper-item v-for="(item, index) in Merchants.images" :key="index">
					<image :src="item" mode="aspectFill" class="swiper-item"></image>
				</swiper-item>
			</swiper>
		</view>
		<view class="shop-show">
			<view class="shop-info">
				<view class="shop-name">{{ Merchants.title }}</view>
				<view class="shop-rating">
					<uni-rate size="18" :readonly="true" :value="star" />
					<text class="shop-score">{{ Merchants.star }}分</text>
					<text class="sales">{{ '销量：' + sales }}</text>
				</view>

				<view class="business-time">{{ Merchants.businessHours }}</view>
				<view class="shop-address">{{ Merchants.detailedAddress }}</view>
			</view>
		</view>
		<!-- 服务部分 -->
		<view class="service-section">
			<view class="section-title">服务</view>
			<checkbox-group @change="checkboxChange">
				<view class="service-item" v-for="(service, index) in services" :key="index">
					<view class="service-checkbox">
						<!-- 使用uni-checkbox组件 -->
						<checkbox :value="service.packageId" :checked="service.checked" />
					</view>
					<view class="service-content">
						<view class="service-name">{{ service.packageName }}</view>
						<view class="service-price">
							<text class="old-price" v-if="service.prince">{{ '￥' + service.prince }}</text>
							<text class="new-price">￥{{ service.prince-service.discountAmount }}</text>
						</view>
					</view>
				</view>
			</checkbox-group>
		</view>
		<!-- 评价部分 -->
		<view class="evaluation-section">
			<view class="section-title">服务评价</view>
			<view class="evaluation-item" v-for="(evaluation, index) in review" :key="index">
				<view class="user-info">
					<text class="user-name">{{ evaluation.user.nickName }}</text>
					<text class="evaluation-time">{{ evaluation.createdAt }}</text>
				</view>
				<view class="rating">
					<uni-rate size="18" :readonly="true" :value="evaluation.rating" />
				</view>
				<view class="evaluation-content">{{ evaluation.content }}</view>
				<view v-if="evaluation.images.length > 0" class="evaluation-images">
					<image :src="image" mode="widthFix" class="evaluation-image"
						v-for="(image, imgIndex) in evaluation.images" :key="imgIndex"></image>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="m-f">
			<view class="button-section">
				<button @tap="showPopup" class="buy-button">购物车({{ cartCount }})</button>
				<button @tap="confirmServices" class="confirm-button">确认已选服务</button>
			</view>
		</view>

		<view>
			<!-- 购物车弹窗 -->
			<uni-popup ref="cartPopup" type="bottom" :safe-area="true">
				<view class="cart-layer">
					<view class="cart-header">
						<text class="cart-title">已选服务（{{ cartCount }}）</text>
						<uni-icons type="close" size="24" @click="closePopup" />
					</view>
					<scroll-view scroll-y class="cart-content">
						<view v-for="(item, index) in cartItems" :key="index" class="cart-item">
							<text class="item-name">{{ item.name }}</text>
							<text class="item-price">￥{{ item.newPrice }}</text>
						</view>
						<view v-if="cartCount === 0" class="empty-tip">暂未选择服务</view>
					</scroll-view>
					<view class="cartCount">总价:{{totalPrice}}</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	const cartCount = ref(0) //套餐数量
	const totalPrice = ref(0); //总价
	const cartPopup = ref(null); // 控制弹出层显示
	// 显示弹出层
	const showPopup = () => {
		cartPopup.value.open();
	};
	// 关闭弹出层
	const closePopup = () => {
		cartPopup.value.close();
	};

	import request from '@/utils/request.js';
	// 购物车功能
	const cartItems = ref([]);
	// 获取数据
	const Merchants = ref({});
	const isCartLayerVisible = ref(false);
	let review = ref([])

	// 监听复选框变化
	const checkboxChange = (e) => {
		const selectedValues = e.detail.value;
		services.value.forEach(service => {
			service.checked = selectedValues.includes(service.packageId.toString());
			// 如果服务被选中，自动加入购物车
			if (service.checked) {
				addToCart(service);
			} else {
				// 如果取消选中，从购物车移除
				removeFromCart(service.packageId);
			}
		});
	};

	// 在 addToCart 和 removeFromCart 方法中更新 totalPrice
	const addToCart = (service) => {
		const existingItem = cartItems.value.find(item => item.packageId === service.packageId);
		if (!existingItem) {
			cartItems.value.push({
				packageId: service.packageId,
				name: service.packageName,
				newPrice: service.prince - service.discountAmount,
				oldPrice: service.prince,
				discountAmount: service.discountAmount
			});
			cartCount.value++;
			totalPrice.value += service.prince - service.discountAmount; // 更新总价
		}
	};

	// 从购物车移除服务
	const removeFromCart = (packageId) => {
		const index = cartItems.value.findIndex(item => item.packageId === packageId);
		if (index !== -1) {
			const removedItem = cartItems.value[index];
			cartItems.value.splice(index, 1);
			cartCount.value--;
			totalPrice.value -= removedItem.newPrice; // 更新总价
		}
	};

	onMounted(() => {
		const data = uni.getStorageSync('maintenancedetail');
		console.log(data);
		if (data) {
			Merchants.value = JSON.parse(data);
			console.log('读取存储的数据:', Merchants);
			// 更新页面数据
			// 例如：
			// title.value = data.title;
			// star.value = data.star;
		}
		request({
			url: `/liu/review/search?merchantId=${Merchants.value.merchantId}`,
			method: 'get',
		}).then(res => {
			console.log('请求成功:', res);
			review.value = res
			console.log("商家", review.value)
		}).catch(err => {
			console.error('请求失败:', err);
		});
		request({
			url: `/liu/packages/serch?merchantId=${Merchants.value.merchantId}`,
			method: 'get',
		}).then(res => {
			console.log('请求成功:', res);
			services.value = res
			console.log("商家", review.value)
		}).catch(err => {
			console.error('请求失败:', err);
		});
	});
	const confirmServices = () => {
		const selectedServices = services.value.filter(service => service.checked);
		if (selectedServices.length === 0) {
			uni.showToast({
				title: '请选择服务',
				icon: 'none'
			});
			return;
		}

		// 将选中的服务信息传递到订单页面
		const cartData = {
			merchantId: Merchants.value.merchantId,
			merchantName: Merchants.value.title,
			totalPrice: totalPrice.value,
			services: selectedServices.map(service => ({
				packageId: service.packageId,
				name: service.packageName,
				price: service.prince - service.discountAmount
			}))
		};

		// 使用uni.setStorageSync将数据存储到本地
		uni.setStorageSync('selectedServices', cartData);
		uni.navigateTo({ // 跳转到订单页面
			url: '/pages/maintenanceorder/maintenanceorder'
		})

	};
	// 店铺信息
	const shopImage = 'https://示例图片地址/店铺图片.jpg'; // 实际替换为真实图片地址
	const shopName = '伟业汽车保养厂(人民路店)';
	const shopScore = '3分';
	const sales = 322;
	const shopAddress = '山阳区人民中路32号';
	const businessTime = '周一至周五 09:00-22:00';

	// 服务列表
	const services = ref([{
		"packageId": 1,
		"packageCode": null,
		"merchantId": 1,
		"packageName": "小保养",
		"discountAmount": 100.00,
		"prince": 1062.56,
		"services": [{
				"serviceId": 1,
				"serviceCategory": 1,
				"serviceCode": "oQZVNDAGaE",
				"serviceName": "名字14",
				"merchantId": 1,
				"merchantName": "Chris West",
				"price": 962.56,
				"description": "fasdfasdfasdfasdfasdfasdf",
				"createdAt": "2016-09-10T04:02:13.000+08:00"
			},
			{
				"serviceId": 2,
				"serviceCategory": 21,
				"serviceCode": "77947728-46ab-43a9-9996-db4201e486cd",
				"serviceName": "精品洗车",
				"merchantId": 1,
				"merchantName": "张三修车店1",
				"price": 60.00,
				"description": "好好的洗车",
				"createdAt": "2025-03-22T10:20:38.000+08:00"
			},
			{
				"serviceId": 3,
				"serviceCategory": 2,
				"serviceCode": "4bd297dc-3d33-4342-b785-d5da22dcaf5c",
				"serviceName": "轮胎按摩",
				"merchantId": 1,
				"merchantName": "张三修车店1",
				"price": 40.00,
				"description": "只按摩后两个轮子",
				"createdAt": "2025-03-22T10:31:36.000+08:00"
			}
		],
		"checked": false
	}]);
</script>

<style>
	.cartCount {

		color: #f6390d;
		width: 100vw;
		background-color: #f5f5f5
	}

	/* 购物车弹窗样式优化 */
	.cart-layer {
		background-color: #fff;
		border-radius: 10px 10px 0 0;
		overflow: hidden;
		position: relative;
		background-color: white;
		bottom: 15px;
		z-index: 999;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}

	.cart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #f5f5f5;
		border-bottom: 1px solid #e0e0e0;
	}

	.cart-title {
		font-size: 18px;
		font-weight: bold;
	}

	.cart-content {
		max-height: 300px;
		background-color: white;
		overflow-y: auto;
	}

	.cart-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		border-bottom: 1px solid #e0e0e0;
	}

	.item-name {
		font-size: 16px;
	}

	.item-price {
		color: #ff5722;
		font-weight: bold;
	}

	.empty-tip {
		text-align: center;
		padding: 20px 0;
		color: #999;
	}

	.cart-footer {
		padding: 15px;
		background-color: #f5f5f5;
		border-top: 1px solid #e0e0e0;
	}

	.checkout-button {
		width: 100%;
		background-color: #ff5722;
		color: white;
		border: none;
		border-radius: 20px;
		padding: 10px 0;
		font-size: 16px;
	}

	.container {
		padding: 15px;
	}

	.shop-show {
		display: flex;
		margin-bottom: 15px;
	}

	.shop-show image {
		width: 100%;
		height: auto;
		max-width: 300px;
		margin-right: 15px;
	}

	.shop-info {
		flex: 1;
		/* 占据剩余空间 */
		display: flex;
		flex-direction: column;
		/* 垂直排列 */
		justify-content: space-between;
		width: 0;
		/* 防止内容溢出 */
	}

	.shop-name {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.shop-rating {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.star-icon {
		width: 20px;
		height: 20px;
		margin-right: 3px;
	}

	.shop-score {
		margin-left: 5px;
	}

	.sales {
		margin-left: 10px;
	}

	.shop-address {
		margin-bottom: 5px;
	}

	.business-time {
		color: #999;
	}

	.section-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.service-item {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		padding: 10px;
		border: 1px solid #e0e0e0;
		border-radius: 5px;
	}

	.service-checkbox {
		margin-right: 10px;
	}

	.service-content {
		flex: 1;
	}

	.service-name {
		font-size: 16px;
		margin-bottom: 5px;
	}

	.old-price {
		text-decoration: line-through;
		color: #999;
		margin-right: 5px;
	}

	.new-price {
		color: red;
	}

	.evaluation-item {
		margin-bottom: 15px;
		padding: 10px;
		border: 1px solid #e0e0e0;
		border-radius: 5px;
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.user-avatar {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		margin-right: 5px;
	}

	.rating {
		margin-bottom: 5px;
	}

	.evaluation-content {
		margin-bottom: 5px;
	}

	.evaluation-images {
		display: flex;
		flex-wrap: wrap;
	}

	.evaluation-image {
		width: 80px;
		height: 80px;
		margin-right: 5px;
		margin-bottom: 5px;
	}

	.m-f {
		position: fixed;
		width: 100%;
		z-index: 1000;
		bottom: 10px;
	}

	.button-section {
		height: 40px;
		width: 92vw;
		line-height: 40px;
		display: flex;
		justify-content: space-between;
	}

	.buy-button {
		flex: 1;
		margin-right: 10px;
		background-color: #f6390d;
		border-radius: 30px;
		color: white;
	}

	.confirm-button {
		flex: 1;
		background-color: #fbab07;
		border-radius: 30px;
		color: white;
	}

	.swiper-container {
		width: 100%;
		height: 100%;
	}

	.swiper-box {
		width: 100%;
		height: 350rpx;
	}

	.swiper-item {
		width: 100%;
		height: 350rpx;
	}
</style>